package com.cms.bs.app.service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.PagedList;
import com.cms.bs.app.model.${name};
import com.cms.bs.app.service.base.BaseService;
import com.cms.bs.common.PageRS;
import com.cms.bs.common.RS;
import com.cms.bs.util.BaseTypeUtil;
import com.cms.bs.util.CommonUtil;
import com.cms.bs.util.JsonUtil;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
* ${name}Service
*/
@Service
public class ${name}Service extends BaseService {

/**
* 创建 ${name}
*
* @param ${v_name}
* @return
*/
public RS create(${name} ${v_name}) {
// 1.1 判断参数是否异常
if (user == null) {
return RS.bad("参数异常.");
}

// 1.2 保存
Ebean.save(${v_name});

return RS.ok();
}

/**
* 删除 ${name}
*
* @param id
* @return
*/
public RS delete(String id) {
if(id!=null){
int delete = 0;
if(id.contains(",")){
delete = Ebean.deleteAll(${name}.class, Arrays.asList(id.split(",")));
}else{
delete = Ebean.delete(${name}.class, id);
}
if (delete > 0) {
return RS.ok();
}
return RS.bad("记录不存在或已被删除.");
}
return RS.bad("参数错误.");
}

/**
* 修改 ${name}
*
* @param ${v_name}
* @return
*/
public RS update(${name} ${v_name}) {
// 1.1 判断参数是否异常
if (user == null || BaseTypeUtil.safeLong(${v_name}.getId()) == 0) {
return RS.bad("参数异常.");
}
// 1.2 判断记录是否存在
int count = Ebean.find(${name}.class).where().eq("id", ${v_name}.getId()).findCount();
if (count <= 0) {
return RS.bad("记录不存在.");
}
// 1.3 更新
Ebean.update(${v_name});

return RS.ok();
}

/**
* 获取 ${name} 详情
*
* @param id
* @return
*/
public RS get(String id) {
${name} ${v_name} = Ebean.find(${name}.class).where().eq("id", id).findUnique();
if(${v_name} != null){
return RS.ok(${v_name});
}
return RS.bad("记录详情获取失败.");
}

/**
* 获取 ${name} 列表： 分页
*
* @param ${v_name}
* @return
*/
public PageRS list(${name} ${v_name}) {
ExpressionList<${name}> expList = Ebean.find(${name}.class).where();

    // 分页
    int pageIndex = 1;
    int pageSize = 100;

    if (${v_name} != null) {
    if (${v_name}.getPageIndex() != null) {
    pageIndex = BaseTypeUtil.safeInt(${v_name}.getPageIndex());
    }
    if (${v_name}.getPageSize() != null) {
    pageSize = BaseTypeUtil.safeInt(${v_name}.getPageSize());
    }
    }

    JSONArray params = JsonUtil.formatJSONArray(${v_name}.getQueryParams());
    if (params != null && params.size() > 0) {
    expList.add(this.addQueryParam(params));
    }
    int rowStart = (pageIndex - 1) * pageSize;
    PagedList<${name}> pagedList = expList.setFirstRow(rowStart).setMaxRows(pageSize).findPagedList();
        int totalRow = pagedList.getTotalCount();
        int totalPage = pagedList.getTotalPageCount();
        return PageRS.ok(pageIndex, pageSize, totalRow, totalPage, pagedList.getList());
        }
        }
